package com.wwwarehouse.taskcenter.fragment.creater_code;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CardDeskTaskResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.fragment.PcImportUnifyFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.FloorBean;
import com.wwwarehouse.taskcenter.bean.GroupBean;
import com.wwwarehouse.taskcenter.bean.LatticeBean;
import com.wwwarehouse.taskcenter.bean.MobileToPcBean;
import com.wwwarehouse.taskcenter.bean.QueryWareBean;
import com.wwwarehouse.taskcenter.bean.WareHouseNameBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/19 15:13
 * @描述 ${TODO}
 */
@Route(path = TaskCenterConstant.CreateWarehouseCodeFragment)
public class CreateWarehouseCodeFragment extends BaseFragment implements View.OnClickListener, TextWatcher, ClearEditText.onMyFocusChangeListener {

    private View                         mView;
    private RelativeLayout               mLlElse;
    private RelativeLayout               mElWareName;
    private ClearEditText                mCetStartFloor;
    private ClearEditText                mCetEndFloor;
    private ClearEditText                mCetStartGrid;
    private ClearEditText                mCetEndGrid;
    private ClearEditText                mCetGroup;
    private StateButton                  mBtSure;
    private StateLayout                  mStateLayout;
    private VirtualKeyboardView          mNumKeyBoard;
    private ElasticScrollView            mElasticScrollView;
    private StateButton                  mBtImport;
    private boolean                      isShow;
    private Map<String, Object>          mCreateCodeMap;
    private RelativeLayout.LayoutParams  mParams;
    private TextView                     mTvWareName;
    private List<String>                 mTestList;
    private List<String>                 mWareNameList;
    private long                       mAbstractObjectUkid;
    private String                       mBusinessId;
    private long                       mDataCodeRuleUkid;
    private PreviewWarehouseCodeFragment mPreviewWarehouseCodeFragment;
    private Bundle                       mToCreateCodeBundle;
    private String mTaskTypeUkid;
    private List<WareHouseNameBean.ListBean> mList;
    private TextInputLayout mTilStartFloor;
    private TextInputLayout mTilEndFloor;
    private TextInputLayout mTilStartGrid;
    private TextInputLayout mTilEndGrid;
    private TextInputLayout mTilGroup;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_warehouse_code, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void getWareHouseName() {
//        mCreateCodeMap.put("ownerUkid", Long.parseLong("10001634"));
        mCreateCodeMap.put("ownerUkid", Long.parseLong(mBusinessId));
        QueryWareBean queryWareBean = new QueryWareBean();
        queryWareBean.setSize(-1);
        mCreateCodeMap.put("query", queryWareBean);
        mCreateCodeMap.put("type", "H_STOCK");
        showProgressDialog();
        NoHttpUtils.httpPost(TaskCenterConstant.GET_WEARHOUSE_INFO, mCreateCodeMap, mOnResponseListener, 0);
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            try {
                switch (i) {
                    case 0:
                        if ("0".equals(commonClass.getCode())) {
                            WareHouseNameBean wareHouseNameBean = JSON.parseObject(commonClass.getData().toString(), WareHouseNameBean.class);
                            mList = wareHouseNameBean.getList();
                            for (int j = 0; j < mList.size(); j++) {
                                mWareNameList.add(mList.get(j).getName());
                            }
                            if (mWareNameList.size() > 0) {
                                showEndPop();
                            } else {
                                toast(mActivity.getResources().getString(R.string.no_ware));
                            }
                        }
                        break;
                    case 1:
                        if ("0".equals(commonClass.getCode())) {
                            mDataCodeRuleUkid = (long)commonClass.getData();
//                            ReadyCodeBean readyCodeBean = JSON.parseObject(commonClass.getData().toString(), ReadyCodeBean.class);
//                            mDataCodeRuleUkid = readyCodeBean.getDataCodeRuleUkid();
                            mToCreateCodeBundle.putLong("dataCodeRuleUkid", mDataCodeRuleUkid);
                            mToCreateCodeBundle.putString("from","function");
                            mPreviewWarehouseCodeFragment.setArguments(mToCreateCodeBundle);
                            popFragment();
                            pushFragment(mPreviewWarehouseCodeFragment);
                        }
                        break;

                    case 2:
                        if ("0".equals(commonClass.getCode())) {
                            MobileToPcBean mobileToPcBean = JSON.parseObject(commonClass.getData().toString(), MobileToPcBean.class);
                            long operationUkid = mobileToPcBean.getOperationUkid();
                            PcImportUnifyFragment pcImportUnifyFragment = new PcImportUnifyFragment();
                            Bundle toPcBundle = new Bundle();
                            CardDeskTaskResponseBean.TaskBean bean = new CardDeskTaskResponseBean.TaskBean();
                            //BelongBusiness ， TaskType ， CardUkid ， CardName
//                            bean.setBelongBusiness("10001634");
                            bean.setBelongBusiness(mBusinessId);
                            bean.setCardUkid(operationUkid+"");
//                            bean.setCardUkid(mTaskTypeUkid);
                            bean.setCardName(mActivity.getResources().getString(R.string.import_ware_code));
                            bean.setTaskType("CREATE_IMPORT_CODE");
                            toPcBundle.putSerializable(Constant.KEY_CARD_DESK_TASK_DETAILS,bean);
                            pcImportUnifyFragment.setArguments(toPcBundle);
                            pushFragment(pcImportUnifyFragment);
                        }
                        break;
                }

            } catch (Exception e) {
                LogUtils.showLog(e.toString());
            }

        }


        @Override
        public void onFailed(String s, int i) {
            toast(s);
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    private void showEndPop() {
        new ChoosePickerDialog.Builder(mActivity).setData(mWareNameList).setTitle(getString(R.string.choose_warehouse)).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
            @Override
            public void onSelected(String itemValue, int position) {
                mTvWareName.setText(mWareNameList.get(position));
                mAbstractObjectUkid = mList.get(position).getAbstractObjectUkid();
            }

            @Override
            public void onCancel() {

            }
        }).create().show();
    }

    private void mobileToPc() {
        Map<String, Object> mobileToPcMap = new HashMap<>();
//        mobileToPcMap.put("businessUnitId", Long.parseLong("10001634"));
        mobileToPcMap.put("businessUnitId", Long.parseLong(mBusinessId));
        mobileToPcMap.put("stockId", mAbstractObjectUkid);
        mobileToPcMap.put("warehouseName", mTvWareName.getText().toString().trim());
        showProgressDialog();
        NoHttpUtils.httpPost(TaskCenterConstant.GOTO_IMPORT_DATA,mobileToPcMap,mOnResponseListener,2);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cet_start_floor || id == R.id.cet_end_floor || id != R.id.cet_start_grid || id != R.id.cet_end_grid || id != R.id.cet_group) {
            mCetStartFloor.clearFocus();
            mCetEndFloor.clearFocus();
            mCetStartGrid.clearFocus();
            mCetEndGrid.clearFocus();
            mCetGroup.clearFocus();
        }
        if (id == R.id.ll_else) {
            canSeeToNoSee();
        } else if (id == R.id.rl_warehouse_name) {
            canSeeToNoSee();
            if (mWareNameList != null && mWareNameList.size() > 0) {
                showEndPop();
            } else {
                getWareHouseName();
            }

        } else if (id == R.id.cet_start_floor) {
            noSeeToCanSee();
        } else if (id == R.id.cet_end_floor) {
            noSeeToCanSee();
        } else if (id == R.id.cet_start_grid) {
            noSeeToCanSee();
        } else if (id == R.id.cet_end_grid) {
            noSeeToCanSee();
        } else if (id == R.id.cet_group) {
            noSeeToCanSee();
        } else if (id == R.id.bt_sure) {
            canSeeToNoSee();
            if ((Integer.parseInt(mCetStartFloor.getText().toString().trim()) > Integer.parseInt(mCetEndFloor.getText().toString().trim())) ||
                    (Integer.parseInt(mCetStartGrid.getText().toString().trim()) > Integer.parseInt(mCetEndGrid.getText().toString().trim()))) {
                toast(mActivity.getResources().getString(R.string.ent_no_start));
            } else {
                getReadCreateCode();
            }

        } else if (id == R.id.bt_import) {
            if (!mActivity.getResources().getString(R.string.select_warehouse).equals(mTvWareName.getText().toString().trim())) {
                mobileToPc();
            } else {
                toast(mActivity.getResources().getString(R.string.please_select_warehouse));
            }

        }
    }

    private void getReadCreateCode() {
        Map<String, Object> readCreateCodeMap = new HashMap<>();
        FloorBean floorBean = new FloorBean();
        floorBean.setFloorDataBegin(Integer.parseInt(mCetStartFloor.getText().toString().trim()));
        floorBean.setFloorDataEnd(Integer.parseInt(mCetEndFloor.getText().toString().trim()));
        GroupBean groupBean = new GroupBean();
        groupBean.setGroupDataBegin(Integer.parseInt(mCetGroup.getText().toString().trim()));
        LatticeBean latticeBean = new LatticeBean();
        latticeBean.setLatticeDataBegin(Integer.parseInt(mCetStartGrid.getText().toString().trim()));
        latticeBean.setLatticeDataEnd(Integer.parseInt(mCetEndGrid.getText().toString().trim()));
        readCreateCodeMap.put("dataType", 0);
        readCreateCodeMap.put("floor", floorBean);
        readCreateCodeMap.put("group", groupBean);
        readCreateCodeMap.put("lattice", latticeBean);
        readCreateCodeMap.put("ownerUkid", Long.parseLong(mBusinessId));
//        readCreateCodeMap.put("ownerUkid", Long.parseLong("10001634"));
        readCreateCodeMap.put("stockId", mAbstractObjectUkid);
        showProgressDialog();
        NoHttpUtils.httpPost(TaskCenterConstant.CREATE_DATA_CODE, readCreateCodeMap, mOnResponseListener, 1);
    }

    private void canSeeToNoSee() {
        if (mNumKeyBoard.getVisibility() == View.VISIBLE) {
            mNumKeyBoard.setVisibility(View.GONE);
        }
    }

    private void noSeeToCanSee() {
        if (mNumKeyBoard.getVisibility() == View.GONE) {
            mNumKeyBoard.setVisibility(View.VISIBLE);
        }
    }

    private void initData() {
        mWareNameList = new ArrayList<>();//存储仓库名字的集合
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {

            }

            @Override
            public void onUpPull() {
                if (mNumKeyBoard.getVisibility() == View.VISIBLE) {
                    mNumKeyBoard.setVisibility(View.GONE);
                }
                if (!isShow) {
                    mBtImport.setVisibility(View.VISIBLE);
                    mParams.setMargins(ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 59));
                    mLlElse.setLayoutParams(mParams);
                    isShow = !isShow;
                } else {
                    mBtImport.setVisibility(View.GONE);
                    mParams.setMargins(ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 36));
                    mLlElse.setLayoutParams(mParams);
                    isShow = !isShow;
                }
            }
        });

    }

    private void initView() {
        mTilStartFloor = findView(mView, R.id.til_start_floor);
        mTilEndFloor = findView(mView, R.id.til_end_floor);
        mTilStartGrid = findView(mView, R.id.til_start_grid);
        mTilEndGrid = findView(mView, R.id.til_end_grid);
        mTilGroup = findView(mView, R.id.til_group);
        mElasticScrollView = findView(mView, R.id.esv_elastic);
        mStateLayout = findView(mView, R.id.sl_layout);
        mLlElse = findView(mView, R.id.ll_else);
        mParams = (RelativeLayout.LayoutParams) mLlElse.getLayoutParams();
        mElWareName = findView(mView, R.id.rl_warehouse_name);
        mTvWareName = findView(mView, R.id.tv_ware_name);
        mCetStartFloor = findView(mView, R.id.cet_start_floor);
        mCetEndFloor = findView(mView, R.id.cet_end_floor);
        mCetStartGrid = findView(mView, R.id.cet_start_grid);
        mCetEndGrid = findView(mView, R.id.cet_end_grid);
        mCetGroup = findView(mView, R.id.cet_group);
        mBtSure = findView(mView, R.id.bt_sure);
        mNumKeyBoard = findView(mView, R.id.number);
        mNumKeyBoard.setOnConfirmListener(new VirtualKeyboardView.OnConfirmListener() {
            @Override
            public void confirm() {
                mNumKeyBoard.setVisibility(View.GONE);
                mCetStartFloor.clearFocus();
                mCetEndFloor.clearFocus();
                mCetStartGrid.clearFocus();
                mCetEndGrid.clearFocus();
                mCetGroup.clearFocus();
            }
        });
        mBtImport = findView(mView, R.id.bt_import);
        mLlElse.setOnClickListener(this);
        mElWareName.setOnClickListener(this);
        mCetStartFloor.setOnClickListener(this);
        mCetEndFloor.setOnClickListener(this);
        mCetStartGrid.setOnClickListener(this);
        mCetEndGrid.setOnClickListener(this);
        mCetGroup.setOnClickListener(this);
        mBtSure.setOnClickListener(this);
        mCetStartFloor.addTextChangedListener(this);
        mCetEndFloor.addTextChangedListener(this);
        mCetStartGrid.addTextChangedListener(this);
        mCetEndGrid.addTextChangedListener(this);
        mCetGroup.addTextChangedListener(this);
        mTvWareName.addTextChangedListener(this);
        mCetStartFloor.setOnMyFocusChangeListener(this);
        mCetEndFloor.setOnMyFocusChangeListener(this);
        mCetStartGrid.setOnMyFocusChangeListener(this);
        mCetEndGrid.setOnMyFocusChangeListener(this);
        mCetGroup.setOnMyFocusChangeListener(this);
        mBtImport.setOnClickListener(this);
        hideSystemKeyboard(mCetStartFloor, mCetEndFloor, mCetStartGrid, mCetEndGrid, mCetGroup);
        //        mTvWareName.setText(String.format("被邀请人: %s真的%s", "wo","ta"));
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof CreateWarehouseCodeFragment) {
            mActivity.setTitle(R.string.create_ware_codes);
        }
    }

    @Override
    public void requestDatas() {
        //获取
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            mTaskTypeUkid = taskBean.getTaskTypeUkid();
            mBusinessId = taskBean.getBusinessId();
        }
        mPreviewWarehouseCodeFragment = new PreviewWarehouseCodeFragment();
        mToCreateCodeBundle = new Bundle();
        mCreateCodeMap = new HashMap();
    }

    private void hideSystemKeyboard(EditText... mNumber) {
        for (int i = 0; i < mNumber.length; i++) {
            // 设置不调用系统键盘
            if (android.os.Build.VERSION.SDK_INT <= 10) {
                mNumber[i].setInputType(InputType.TYPE_NULL);
            } else {
                mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                Class<EditText> clazz = EditText.class;
                Method method;

                try {
                    method = clazz.getMethod("setShowSoftInputOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    method = clazz.getMethod("setSoftInputShownOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mCetStartFloor.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCetEndFloor.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCetStartGrid.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCetEndGrid.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCetGroup.getText().toString().trim()) &&
                !mActivity.getResources().getString(R.string.select_warehouse).equals(mTvWareName.getText().toString().trim())) {
            mBtSure.setEnabled(true);
        } else {
            mBtSure.setEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onFocusChange(View view, boolean b) {
        int id = view.getId();
        if (id == R.id.cet_start_floor) {
            if (b) {
                noSeeToCanSee();
                mNumKeyBoard.setEditText((ClearEditText) view);
            } else {
                if (!TextUtils.isEmpty(mCetStartFloor.getText().toString().trim())) {
                    if (isPositiveInteger(mCetStartFloor.getText().toString().trim())) {
                        mTilStartFloor.setStateNormal();
                    } else {
                        mTilStartFloor.setStateWrong(mActivity.getResources().getString(R.string.no_rule_text));
                        mBtSure.setEnabled(false);
                    }
                }

            }
        } else if (id == R.id.cet_end_floor) {
            if (b) {
                noSeeToCanSee();
                mNumKeyBoard.setEditText((ClearEditText) view);
            } else {
                if (!TextUtils.isEmpty(mCetEndFloor.getText().toString().trim())) {
                    if (isPositiveInteger(mCetEndFloor.getText().toString().trim())) {
                        mTilEndFloor.setStateNormal();
                    } else {
                        mTilEndFloor.setStateWrong(mActivity.getResources().getString(R.string.no_rule_text));
                        mBtSure.setEnabled(false);
                    }
                }

            }
        } else if (id == R.id.cet_start_grid) {
            if (b) {
                noSeeToCanSee();
                mNumKeyBoard.setEditText((ClearEditText) view);
            } else {
                if (!TextUtils.isEmpty(mCetStartGrid.getText().toString().trim())) {
                    if (isPositiveInteger(mCetStartGrid.getText().toString().trim())) {
                        mTilStartGrid.setStateNormal();
                    } else {
                        mTilStartGrid.setStateWrong(mActivity.getResources().getString(R.string.no_rule_text));
                        mBtSure.setEnabled(false);
                    }
                }

            }
        } else if (id == R.id.cet_end_grid) {
            if (b) {
                noSeeToCanSee();
                mNumKeyBoard.setEditText((ClearEditText) view);
            } else {
                if (!TextUtils.isEmpty(mCetEndGrid.getText().toString().trim())) {
                    if (isPositiveInteger(mCetEndGrid.getText().toString().trim())) {
                        mTilEndGrid.setStateNormal();
                    } else {
                        mTilEndGrid.setStateWrong(mActivity.getResources().getString(R.string.no_rule_text));
                        mBtSure.setEnabled(false);
                    }
                }

            }
        } else if (id == R.id.cet_group) {
            if (b) {
                noSeeToCanSee();
                mNumKeyBoard.setEditText((ClearEditText) view);
            } else {
                if (!TextUtils.isEmpty(mCetGroup.getText().toString().trim())) {
                    if (isPositiveInteger(mCetGroup.getText().toString().trim())) {
                        mTilGroup.setStateNormal();
                    } else {
                        mTilGroup.setStateWrong(mActivity.getResources().getString(R.string.no_rule_text));
                        mBtSure.setEnabled(false);
                    }
                }

            }

        }
    }

    private boolean isPositiveInteger(String s){
        String pattern = "[1-9]\\d*";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(s);
        boolean matches = m.matches();
        if (matches) {
            return true;
        }
        return false;
    }

}
